package com.bumptech.glide.load.resource.bitmap;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.ColorSpace;
import android.graphics.ColorSpace.Named;
import android.os.Build.VERSION;
import android.util.DisplayMetrics;
import android.util.Log;
import androidx.annotation.Nullable;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.ImageHeaderParser;
import com.bumptech.glide.load.ImageHeaderParser.ImageType;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import o.aaq;
import o.aas;
import o.aau;
import o.rx;
import o.sb;
import o.sc;
import o.sf;
import o.tx;
import o.uc;
import o.ud;
import o.wh;
import o.wu;
import o.wu.h;
import o.wx;
import o.xb;

public final class Downsampler {
    public static final sb<Boolean> ALLOW_HARDWARE_CONFIG = sb.ˎ("com.bumptech.glide.load.resource.bitmap.Downsampler.AllowHardwareDecode", Boolean.valueOf(false));
    public static final sb<DecodeFormat> DECODE_FORMAT = sb.ˎ("com.bumptech.glide.load.resource.bitmap.Downsampler.DecodeFormat", DecodeFormat.DEFAULT);
    @Deprecated
    public static final sb<wu> DOWNSAMPLE_STRATEGY = wu.ʼ;
    private static final e EMPTY_CALLBACKS = new e() {
        public void ॱ() {
        }

        public void ˋ(uc ucVar, Bitmap bitmap) {
        }
    };
    public static final sb<Boolean> FIX_BITMAP_SIZE_TO_REQUESTED_DIMENSIONS = sb.ˎ("com.bumptech.glide.load.resource.bitmap.Downsampler.FixBitmapSize", Boolean.valueOf(false));
    private static final String ICO_MIME_TYPE = "image/x-ico";
    private static final int MARK_POSITION = 10485760;
    private static final Set<String> NO_DOWNSAMPLE_PRE_N_MIME_TYPES = Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[]{WBMP_MIME_TYPE, ICO_MIME_TYPE})));
    private static final Queue<Options> OPTIONS_QUEUE = aau.ॱ(0);
    public static final sb<sf> PREFERRED_COLOR_SPACE = sb.ˎ("com.bumptech.glide.load.resource.bitmap.Downsampler.PreferredColorSpace", sf.SRGB);
    static final String TAG = "Downsampler";
    private static final Set<ImageType> TYPES_THAT_USE_POOL_PRE_KITKAT = Collections.unmodifiableSet(EnumSet.of(ImageType.JPEG, ImageType.PNG_A, ImageType.PNG));
    private static final String WBMP_MIME_TYPE = "image/vnd.wap.wbmp";
    private final uc bitmapPool;
    private final ud byteArrayPool;
    private final DisplayMetrics displayMetrics;
    private final wx hardwareConfigState = wx.ˊ();
    private final List<ImageHeaderParser> parsers;

    public interface e {
        void ˋ(uc ucVar, Bitmap bitmap) throws IOException;

        void ॱ();
    }

    public Downsampler(List<ImageHeaderParser> list, DisplayMetrics displayMetrics, uc ucVar, ud udVar) {
        this.parsers = list;
        this.displayMetrics = (DisplayMetrics) aas.ˎ(displayMetrics);
        this.bitmapPool = (uc) aas.ˎ(ucVar);
        this.byteArrayPool = (ud) aas.ˎ(udVar);
    }

    public boolean handles(InputStream inputStream) {
        return true;
    }

    public boolean handles(ByteBuffer byteBuffer) {
        return true;
    }

    public tx<Bitmap> decode(InputStream inputStream, int i, int i2, sc scVar) throws IOException {
        return decode(inputStream, i, i2, scVar, EMPTY_CALLBACKS);
    }

    public tx<Bitmap> decode(InputStream inputStream, int i, int i2, sc scVar, e eVar) throws IOException {
        boolean z;
        aas.ˏ(inputStream.markSupported(), "You must provide an InputStream that supports mark()");
        byte[] bArr = (byte[]) this.byteArrayPool.ॱ(WXMediaMessage.THUMB_LENGTH_LIMIT, byte[].class);
        Options defaultOptions = getDefaultOptions();
        defaultOptions.inTempStorage = bArr;
        DecodeFormat decodeFormat = (DecodeFormat) scVar.ॱ(DECODE_FORMAT);
        sf sfVar = (sf) scVar.ॱ(PREFERRED_COLOR_SPACE);
        wu wuVar = (wu) scVar.ॱ(wu.ʼ);
        boolean booleanValue = ((Boolean) scVar.ॱ(FIX_BITMAP_SIZE_TO_REQUESTED_DIMENSIONS)).booleanValue();
        if (scVar.ॱ(ALLOW_HARDWARE_CONFIG) != null) {
            if (((Boolean) scVar.ॱ(ALLOW_HARDWARE_CONFIG)).booleanValue()) {
                z = true;
                tx<Bitmap> ˊ = wh.ˊ(decodeFromWrappedStreams(inputStream, defaultOptions, wuVar, decodeFormat, sfVar, z, i, i2, booleanValue, eVar), this.bitmapPool);
                return ˊ;
            }
        }
        z = false;
        try {
            tx<Bitmap> ˊ2 = wh.ˊ(decodeFromWrappedStreams(inputStream, defaultOptions, wuVar, decodeFormat, sfVar, z, i, i2, booleanValue, eVar), this.bitmapPool);
            return ˊ2;
        } finally {
            releaseOptions(defaultOptions);
            this.byteArrayPool.ˊ(bArr);
        }
    }

    private Bitmap decodeFromWrappedStreams(InputStream inputStream, Options options, wu wuVar, DecodeFormat decodeFormat, sf sfVar, boolean z, int i, int i2, boolean z2, e eVar) throws IOException {
        boolean z3;
        long ॱ = aaq.ॱ();
        int[] dimensions = getDimensions(inputStream, options, eVar, this.bitmapPool);
        int i3 = dimensions[0];
        int i4 = dimensions[1];
        String str = options.outMimeType;
        if (i3 == -1 || i4 == -1) {
            z3 = false;
        } else {
            z3 = z;
        }
        int ˎ = rx.ˎ(this.parsers, inputStream, this.byteArrayPool);
        int ˊ = xb.ˊ(ˎ);
        boolean ˎ2 = xb.ˎ(ˎ);
        int i5 = i == Integer.MIN_VALUE ? isRotationRequired(ˊ) ? i4 : i3 : i;
        int i6 = i2 == Integer.MIN_VALUE ? isRotationRequired(ˊ) ? i3 : i4 : i2;
        ImageType ˏ = rx.ˏ(this.parsers, inputStream, this.byteArrayPool);
        calculateScaling(ˏ, inputStream, eVar, this.bitmapPool, wuVar, ˊ, i3, i4, i5, i6, options);
        calculateConfig(inputStream, decodeFormat, z3, ˎ2, options, i5, i6);
        Object obj = VERSION.SDK_INT >= 19 ? 1 : null;
        if ((options.inSampleSize == 1 || obj != null) && shouldUsePool(ˏ)) {
            if (i3 < 0 || i4 < 0 || !z2 || obj == null) {
                float f = isScaling(options) ? ((float) options.inTargetDensity) / ((float) options.inDensity) : 1.0f;
                int i7 = options.inSampleSize;
                int ceil = (int) Math.ceil((double) (((float) i4) / ((float) i7)));
                i5 = Math.round(((float) ((int) Math.ceil((double) (((float) i3) / ((float) i7))))) * f);
                i6 = Math.round(((float) ceil) * f);
                if (Log.isLoggable(TAG, 2)) {
                    Log.v(TAG, "Calculated target [" + i5 + "x" + i6 + "] for source [" + i3 + "x" + i4 + "], sampleSize: " + i7 + ", targetDensity: " + options.inTargetDensity + ", density: " + options.inDensity + ", density multiplier: " + f);
                }
            }
            if (i5 > 0 && i6 > 0) {
                setInBitmap(options, this.bitmapPool, i5, i6);
            }
        }
        if (VERSION.SDK_INT >= 28) {
            Object obj2 = (sfVar == sf.DISPLAY_P3 && options.outColorSpace != null && options.outColorSpace.isWideGamut()) ? 1 : null;
            options.inPreferredColorSpace = ColorSpace.get(obj2 != null ? Named.DISPLAY_P3 : Named.SRGB);
        } else if (VERSION.SDK_INT >= 26) {
            options.inPreferredColorSpace = ColorSpace.get(Named.SRGB);
        }
        Bitmap decodeStream = decodeStream(inputStream, options, eVar, this.bitmapPool);
        eVar.ˋ(this.bitmapPool, decodeStream);
        if (Log.isLoggable(TAG, 2)) {
            logDecode(i3, i4, str, options, decodeStream, i, i2, ॱ);
        }
        Bitmap bitmap = null;
        if (decodeStream != null) {
            decodeStream.setDensity(this.displayMetrics.densityDpi);
            bitmap = xb.ˋ(this.bitmapPool, decodeStream, ˎ);
            if (!decodeStream.equals(bitmap)) {
                this.bitmapPool.ˏ(decodeStream);
            }
        }
        return bitmap;
    }

    private static void calculateScaling(ImageType imageType, InputStream inputStream, e eVar, uc ucVar, wu wuVar, int i, int i2, int i3, int i4, int i5, Options options) throws IOException {
        if (i2 > 0 && i3 > 0) {
            int i6;
            int i7;
            if (isRotationRequired(i)) {
                i6 = i2;
                i7 = i3;
            } else {
                i6 = i3;
                i7 = i2;
            }
            float ˎ = wuVar.ˎ(i7, i6, i4, i5);
            if (ˎ <= 0.0f) {
                throw new IllegalArgumentException("Cannot scale with factor: " + ˎ + " from: " + wuVar + ", source: [" + i2 + "x" + i3 + "], target: [" + i4 + "x" + i5 + "]");
            }
            h ˏ = wuVar.ˏ(i7, i6, i4, i5);
            if (ˏ == null) {
                throw new IllegalArgumentException("Cannot round with null rounding");
            }
            int round = i7 / round((double) (((float) i7) * ˎ));
            int round2 = i6 / round((double) (((float) i6) * ˎ));
            if (ˏ == h.MEMORY) {
                round = Math.max(round, round2);
            } else {
                round = Math.min(round, round2);
            }
            if (VERSION.SDK_INT > 23 || !NO_DOWNSAMPLE_PRE_N_MIME_TYPES.contains(options.outMimeType)) {
                round = Math.max(1, Integer.highestOneBit(round));
                if (ˏ == h.MEMORY && ((float) round) < 1.0f / ˎ) {
                    round <<= 1;
                }
            } else {
                round = 1;
            }
            options.inSampleSize = round;
            if (imageType == ImageType.JPEG) {
                int min = Math.min(round, 8);
                i7 = (int) Math.ceil((double) (((float) i7) / ((float) min)));
                i6 = (int) Math.ceil((double) (((float) i6) / ((float) min)));
                min = round / 8;
                if (min > 0) {
                    i7 /= min;
                    i6 /= min;
                }
            } else if (imageType == ImageType.PNG || imageType == ImageType.PNG_A) {
                i7 = (int) Math.floor((double) (((float) i7) / ((float) round)));
                i6 = (int) Math.floor((double) (((float) i6) / ((float) round)));
            } else if (imageType == ImageType.WEBP || imageType == ImageType.WEBP_A) {
                if (VERSION.SDK_INT >= 24) {
                    i7 = Math.round(((float) i7) / ((float) round));
                    i6 = Math.round(((float) i6) / ((float) round));
                } else {
                    i7 = (int) Math.floor((double) (((float) i7) / ((float) round)));
                    i6 = (int) Math.floor((double) (((float) i6) / ((float) round)));
                }
            } else if (i7 % round == 0 && i6 % round == 0) {
                i7 /= round;
                i6 /= round;
            } else {
                int[] dimensions = getDimensions(inputStream, options, eVar, ucVar);
                i7 = dimensions[0];
                i6 = dimensions[1];
            }
            double ˎ2 = (double) wuVar.ˎ(i7, i6, i4, i5);
            if (VERSION.SDK_INT >= 19) {
                options.inTargetDensity = adjustTargetDensityForError(ˎ2);
                options.inDensity = getDensityMultiplier(ˎ2);
            }
            if (isScaling(options)) {
                options.inScaled = true;
            } else {
                options.inTargetDensity = 0;
                options.inDensity = 0;
            }
            if (Log.isLoggable(TAG, 2)) {
                Log.v(TAG, "Calculate scaling, source: [" + i2 + "x" + i3 + "], degreesToRotate: " + i + ", target: [" + i4 + "x" + i5 + "], power of two scaled: [" + i7 + "x" + i6 + "], exact scale factor: " + ˎ + ", power of 2 sample size: " + round + ", adjusted scale factor: " + ˎ2 + ", target density: " + options.inTargetDensity + ", density: " + options.inDensity);
            }
        } else if (Log.isLoggable(TAG, 3)) {
            Log.d(TAG, "Unable to determine dimensions for: " + imageType + " with target [" + i4 + "x" + i5 + "]");
        }
    }

    private static int adjustTargetDensityForError(double d) {
        int densityMultiplier = getDensityMultiplier(d);
        int round = round(((double) densityMultiplier) * d);
        return round(((double) round) * (d / ((double) (((float) round) / ((float) densityMultiplier)))));
    }

    private static int getDensityMultiplier(double d) {
        if (d > 1.0d) {
            d = 1.0d / d;
        }
        return (int) Math.round(2.147483647E9d * d);
    }

    private static int round(double d) {
        return (int) (0.5d + d);
    }

    private boolean shouldUsePool(ImageType imageType) {
        if (VERSION.SDK_INT >= 19) {
            return true;
        }
        return TYPES_THAT_USE_POOL_PRE_KITKAT.contains(imageType);
    }

    private void calculateConfig(InputStream inputStream, DecodeFormat decodeFormat, boolean z, boolean z2, Options options, int i, int i2) {
        if (!this.hardwareConfigState.ˏ(i, i2, options, z, z2)) {
            if (decodeFormat == DecodeFormat.PREFER_ARGB_8888 || VERSION.SDK_INT == 16) {
                options.inPreferredConfig = Config.ARGB_8888;
                return;
            }
            boolean hasAlpha;
            try {
                hasAlpha = rx.ˏ(this.parsers, inputStream, this.byteArrayPool).hasAlpha();
            } catch (Throwable e) {
                if (Log.isLoggable(TAG, 3)) {
                    Log.d(TAG, "Cannot determine whether the image has alpha or not from header, format " + decodeFormat, e);
                }
                hasAlpha = false;
            }
            options.inPreferredConfig = hasAlpha ? Config.ARGB_8888 : Config.RGB_565;
            if (options.inPreferredConfig == Config.RGB_565) {
                options.inDither = true;
            }
        }
    }

    private static int[] getDimensions(InputStream inputStream, Options options, e eVar, uc ucVar) throws IOException {
        options.inJustDecodeBounds = true;
        decodeStream(inputStream, options, eVar, ucVar);
        options.inJustDecodeBounds = false;
        return new int[]{options.outWidth, options.outHeight};
    }

    private static Bitmap decodeStream(InputStream inputStream, Options options, e eVar, uc ucVar) throws IOException {
        Bitmap decodeStream;
        Object newIoExceptionForInBitmapAssertion;
        if (options.inJustDecodeBounds) {
            inputStream.mark(MARK_POSITION);
        } else {
            eVar.ॱ();
        }
        int i = options.outWidth;
        int i2 = options.outHeight;
        String str = options.outMimeType;
        xb.ˊ().lock();
        try {
            decodeStream = BitmapFactory.decodeStream(inputStream, null, options);
            xb.ˊ().unlock();
            if (options.inJustDecodeBounds) {
                inputStream.reset();
            }
        } catch (IOException e) {
            throw newIoExceptionForInBitmapAssertion;
        } catch (IllegalArgumentException e2) {
            newIoExceptionForInBitmapAssertion = newIoExceptionForInBitmapAssertion(e2, i, i2, str, options);
            if (Log.isLoggable(TAG, 3)) {
                Log.d(TAG, "Failed to decode with inBitmap, trying again without Bitmap re-use", newIoExceptionForInBitmapAssertion);
            }
            if (options.inBitmap != null) {
                inputStream.reset();
                ucVar.ˏ(options.inBitmap);
                options.inBitmap = null;
                decodeStream = decodeStream(inputStream, options, eVar, ucVar);
                xb.ˊ().unlock();
            } else {
                throw newIoExceptionForInBitmapAssertion;
            }
        } catch (Throwable th) {
            xb.ˊ().unlock();
        }
        return decodeStream;
    }

    private static boolean isScaling(Options options) {
        return options.inTargetDensity > 0 && options.inDensity > 0 && options.inTargetDensity != options.inDensity;
    }

    private static void logDecode(int i, int i2, String str, Options options, Bitmap bitmap, int i3, int i4, long j) {
        Log.v(TAG, "Decoded " + getBitmapString(bitmap) + " from [" + i + "x" + i2 + "] " + str + " with inBitmap " + getInBitmapString(options) + " for [" + i3 + "x" + i4 + "], sample size: " + options.inSampleSize + ", density: " + options.inDensity + ", target density: " + options.inTargetDensity + ", thread: " + Thread.currentThread().getName() + ", duration: " + aaq.ˎ(j));
    }

    private static String getInBitmapString(Options options) {
        return getBitmapString(options.inBitmap);
    }

    @TargetApi(19)
    @Nullable
    private static String getBitmapString(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        String str;
        if (VERSION.SDK_INT >= 19) {
            str = " (" + bitmap.getAllocationByteCount() + ")";
        } else {
            str = "";
        }
        return "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig() + str;
    }

    private static IOException newIoExceptionForInBitmapAssertion(IllegalArgumentException illegalArgumentException, int i, int i2, String str, Options options) {
        return new IOException("Exception decoding bitmap, outWidth: " + i + ", outHeight: " + i2 + ", outMimeType: " + str + ", inBitmap: " + getInBitmapString(options), illegalArgumentException);
    }

    @TargetApi(26)
    private static void setInBitmap(Options options, uc ucVar, int i, int i2) {
        Config config = null;
        if (VERSION.SDK_INT >= 26) {
            if (options.inPreferredConfig != Config.HARDWARE) {
                config = options.outConfig;
            } else {
                return;
            }
        }
        if (config == null) {
            config = options.inPreferredConfig;
        }
        options.inBitmap = ucVar.ॱ(i, i2, config);
    }

    private static synchronized Options getDefaultOptions() {
        Options options;
        synchronized (Downsampler.class) {
            synchronized (OPTIONS_QUEUE) {
                options = (Options) OPTIONS_QUEUE.poll();
            }
            if (options == null) {
                options = new Options();
                resetOptions(options);
            }
        }
        return options;
    }

    private static void releaseOptions(Options options) {
        resetOptions(options);
        synchronized (OPTIONS_QUEUE) {
            OPTIONS_QUEUE.offer(options);
        }
    }

    private static void resetOptions(Options options) {
        options.inTempStorage = null;
        options.inDither = false;
        options.inScaled = false;
        options.inSampleSize = 1;
        options.inPreferredConfig = null;
        options.inJustDecodeBounds = false;
        options.inDensity = 0;
        options.inTargetDensity = 0;
        if (VERSION.SDK_INT >= 26) {
            options.inPreferredColorSpace = null;
            options.outColorSpace = null;
            options.outConfig = null;
        }
        options.outWidth = 0;
        options.outHeight = 0;
        options.outMimeType = null;
        options.inBitmap = null;
        options.inMutable = true;
    }

    private static boolean isRotationRequired(int i) {
        return i == 90 || i == 270;
    }
}
